package cn.wubo.multi.thread.demo01;

/**
 * 死锁
 * 什么是死锁：不同的线程分别占用对方需要的同步资源不放弃，都在等待对方放弃自己需要的同步资源，形成了线程的死锁。
 * 死锁的表现：出现死锁后不会出现异常，不会出现提示，只是所有的线程都处于阻塞状态，无法继续。
 */
public class Demo0106 {

    public static void main(String[] args) {

        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = new StringBuffer();

        Thread thread1 = new Thread(() -> {
            synchronized (s1) {
                s1.append("a");
                System.out.println(Thread.currentThread().getName() + " " + s1);
                s2.append("b");
                System.out.println(Thread.currentThread().getName() + " " + s2);
                try {//增加死锁的概率
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (s2) {
                    s1.append("b");
                    System.out.println(Thread.currentThread().getName() + " " + s1);
                    s2.append("c");
                    System.out.println(Thread.currentThread().getName() + " " + s2);
                }
            }
        }, "Thread1");

        Thread thread2 = new Thread(() -> {
            synchronized (s2) {
                s1.append("a");
                System.out.println(Thread.currentThread().getName() + " " + s1);
                s2.append("b");
                System.out.println(Thread.currentThread().getName() + " " + s2);
                try {//增加死锁的概率
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (s1) {
                    s1.append("b");
                    System.out.println(Thread.currentThread().getName() + " " + s1);
                    s2.append("c");
                    System.out.println(Thread.currentThread().getName() + " " + s2);
                }
            }
        }, "Thread2");

        thread1.start();
        thread2.start();
    }
}
